package rpc

import (
	"bytes"
	"strconv"
	"sync"
)

type HttpCodec struct {
	Parser *HTTPParser
	OutBuf *bytes.Buffer
	Head   *bytes.Buffer
	Finish bool
	Body   *bytes.Buffer
	TmpBuf []byte
	FixBuf []byte
}

// 8k*5000=
const LargeBufferSize = 1024 * 8

var HttpCodecPool = sync.Pool{
	New: func() interface{} {
		return NewHttpCodec()
	},
}

func NewHttpCodec() *HttpCodec {
	return &HttpCodec{
		OutBuf: new(bytes.Buffer),
		Parser: NewHTTPParser(),
		Head:   new(bytes.Buffer),
		Finish: true,
		Body:   new(bytes.Buffer),
		TmpBuf: make([]byte, LargeBufferSize),
		FixBuf: make([]byte, LargeBufferSize),
	}
}

func (hc *HttpCodec) Reset() {
	hc.OutBuf.Reset()
	hc.Head.Reset()
	hc.Body.Reset()
	hc.Parser.Reset()
}

func (hc *HttpCodec) AppendResponse() {
	hc.OutBuf.WriteString("HTTP/1.1 200 OK\r\nServer: raft\r\nContent-Type: text/plain;charset=UTF-8\r\nDate: ")
	hc.OutBuf.WriteString("\r\nContent-Length: 12\r\n\r\nHello World!")
}

func (hc *HttpCodec) Append200TextData(data []byte) {
	hc.OutBuf.WriteString("HTTP/1.1 200 OK\r\nServer: raft\r\nContent-Type: text/plain;charset=UTF-8")
	hc.OutBuf.WriteString("\r\nContent-Length: " + strconv.Itoa(len(data)) + "\r\n\r\n")
	hc.OutBuf.Write(data)
}

func (hc *HttpCodec) Append200JsonData(data []byte) {
	hc.OutBuf.WriteString("HTTP/1.1 200 OK\r\nServer: raft\r\nContent-Type: application/json;charset=UTF-8")
	hc.OutBuf.WriteString("\r\nContent-Length: " + strconv.Itoa(len(data)) + "\r\n\r\n")
	hc.OutBuf.Write(data)
}

func (hc *HttpCodec) Append404Text() {
	hc.OutBuf.WriteString("HTTP/1.1 404 Not Found\r\nServer: raft\r\nContent-Type: text/plain;charset=UTF-8\r\nContent-Length: 0\r\n\r\n")
}

func (hc *HttpCodec) Append200Text() {
	hc.OutBuf.WriteString("HTTP/1.1 200 OK\r\nServer: raft\r\nContent-Type: text/plain;charset=UTF-8\r\nContent-Length: 0\r\n\r\n")
}

func (hc *HttpCodec) Append400Text() {
	hc.OutBuf.WriteString("HTTP/1.1 400 Bad Request\r\nServer: raft\r\nContent-Type: text/plain;charset=UTF-8\r\nContent-Length: 0\r\n\r\n")
}
